package com.coco.goods.service.impl;


import com.alibaba.fastjson.JSON;
import com.coco.common.constant.Constant;
import com.coco.common.result.ResultData;
import com.coco.common.util.IdWorker;
import com.coco.goods.feign.PostageFeignService;
import com.coco.goods.mapper.GoodsDescMapper;
import com.coco.goods.mapper.GoodsMapper;
import com.coco.goods.mapper.GoodsSpecMapper;
import com.coco.goods.mapper.GoodsSpecsMapper;
import com.coco.goods.pojo.*;
import com.coco.goods.service.GoodsService;
import com.coco.goods.vo.GoodsSearchVo;
import com.coco.goods.vo.GoodsVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 服务实现层
 *
 * @author Administrator
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired(required = false)
    private GoodsMapper goodsMapper;
    /**
     * 单规格
     */
    @Autowired(required = false)
    private GoodsSpecMapper goodsSpecMapper;
    /**
     * 多规格
     */
    @Autowired(required = false)
    private GoodsSpecsMapper specsMapper;
    /**
     * 商品描述
     */
    @Autowired(required = false)
    private GoodsDescMapper goodsDescMapper;
    /**
     * 雪花算法
     */
    @Autowired
    private IdWorker idWorker;
    /**
     * 运费模板添加
     */
    @Autowired
    private PostageFeignService postageFeignService;


    /**
     * 增加
     */
    @Override
    public void add(TbGoods goods) {

    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void delete(String[] ids) {
        for (String id : ids) {
            goodsMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 修改
     */
    @Override
    public void update(GoodsVo goodsVo) {
        //获取spu信息
        TbGoods goods = goodsVo.getGoods();
        goods.setUpdateTime(new Date());
        //获取商品描述
        TbGoodsDesc goodsDesc = goodsVo.getGoodsDesc();
        //修改商品描述
        goodsDescMapper.updateById(goodsDesc);
        //删除sku表和运费模板
        specsMapper.deleteByGid(goods.getId());
        goodsSpecMapper.deleteByGid(goods.getId());
        postageFeignService.deleteByGid(goods.getId());
        //添加sku信息
        addSku(goodsVo, goods);
        //修改信息
        goodsMapper.updateByPrimaryKey(goods);

    }

    private void addSku(GoodsVo goodsVo, TbGoods goods) {
        //判断是否为单规格
        if (Constant.GoodsConstant.SINGLE_SPECIFICATION.equals(goods.getSpecStatus())) {
            /**
             * 单规格
             */
            TbGoodsSpec goodsSpec = goodsVo.getGoodsSpec();
            //初始化sku
            goodsSpec.setGid(goods.getId());
            goodsSpec.setTitle(goods.getSpuName());
            //添加单规格
            goodsSpecMapper.addGoodsSpec(goodsSpec);
            //初始化spu的值
            goods.setSpuPrice(goodsSpec.getSellingPrice());
            goods.setRepertory(goodsSpec.getStockCount());

        } else {
            /**
             * 多规格
             */
            //获取sku集合
            List<TbGoodsSpecs> goodsSpecsList = goodsVo.getGoodsSpecsList();
            if (goodsSpecsList != null) {
                //初始化spu信息
                goods.setSpuPrice(goodsSpecsList.stream().map(TbGoodsSpecs::getSellingPrice).min((e1, e2) -> e1.compareTo(e2)).get());
                //库存
                goods.setRepertory(goodsSpecsList.stream().mapToInt(TbGoodsSpecs::getStockCount).sum());

                //添加商品sku
                goodsSpecsList.forEach(item -> {
                    //spuid赋值
                    item.setGid(goods.getId());
                    //sku标题
                    String title = goods.getSpuName();
                    Map<String, String> specsList = item.getSpecsList();
                    Set<String> strings = specsList.keySet();
                    for (String key : strings) {
                        title += "" + key + " " + specsList.get(key);
                    }
                    String s = JSON.toJSONString(specsList);
                    item.setSpecs(s);
                    item.setTitle(title);
                    //添加sku信息
                    specsMapper.addGoodsSpecs(item);
                });
            }
        }

        //运费模板
        //添加
        if (goodsVo.getPostageList() != null && goodsVo.getPostageList().size() > 0) {
            goodsVo.getPostageList().forEach(item -> {
                item.setGoodsId(goods.getId());
                item.setType(goods.getIsPostage());
                postageFeignService.add(item);
            });
        }

    }


    /**
     * 根据ID获取实体
     *
     * @param id
     * @return
     */
    @Override
    public GoodsVo findOne(String id) {
        //创建返回对象
        GoodsVo goodsVo = new GoodsVo();
        //查询spu信息
        TbGoods goods = goodsMapper.findOne(id);
        goodsVo.setGoods(goods);
        //查询商品描述信息
        TbGoodsDesc goodsDesc = goodsDescMapper.findById(id);
        goodsVo.setGoodsDesc(goodsDesc);
        //判断是单规格还是多规格
        if (Constant.GoodsConstant.SINGLE_SPECIFICATION.equals(goods.getSpecStatus())) {
            /**
             * 单规格
             */
            TbGoodsSpec goodsSpec = goodsSpecMapper.findByGid(goods.getId());
            goodsVo.setGoodsSpec(goodsSpec);
        } else {
            /**
             * 多规格
             */
            List<TbGoodsSpecs> goodsSpecsList = specsMapper.findByGid(id);
            goodsVo.setGoodsSpecsList(goodsSpecsList);
        }
        //运费模板
        List<TbPostage> tbPostageList = postageFeignService.findByGid(id);
        goodsVo.setPostageList(tbPostageList);

        return goodsVo;
    }

    /**
     * 查询全部
     */
    @Override
    public List<TbGoods> findAll() {
        return goodsMapper.findAll();
    }

    /**
     * 查询全部带条件
     */
    @Override
    public List<TbGoods> findAll(TbGoods goods) {
        return goodsMapper.selectByExample(goods);
    }

    /**
     * 分页模糊
     */
    @Override
    public List<TbGoods> findAllSearch(TbGoods goods) {
        PageHelper.startPage(goods.getPage(), goods.getLimit());
        return goodsMapper.selectByExample(goods);
    }

    /**
     * 上下架商品
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public boolean putAway(String id, Integer status) {
        return goodsMapper.putAway(id, status);
    }

    /**
     * 出售中商品
     *
     * @param goodsSearchVo
     * @return
     */
    @Override
    public ResultData saleList(GoodsSearchVo goodsSearchVo) {
        PageHelper.startPage(goodsSearchVo.getPage(), goodsSearchVo.getLimit());
        List<TbGoods> tbGoods = goodsMapper.saleList(goodsSearchVo);
        PageInfo<TbGoods> pageInfo = new PageInfo<>(tbGoods);
        return new ResultData(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 售罄商品
     *
     * @param goodsSearchVo
     * @return
     */
    @Override
    public ResultData findSelloutGoods(GoodsSearchVo goodsSearchVo) {
        PageInfo<TbGoods> pageInfo = pageAndFuzzy(goodsSearchVo, Constant.GoodsConstant.SELL_OUT);
        return new ResultData(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 回收商品
     *
     * @param goodsSearchVo
     * @return
     */
    @Override
    public ResultData findRecycleGoods(GoodsSearchVo goodsSearchVo) {
        PageInfo<TbGoods> pageInfo = pageAndFuzzy(goodsSearchVo, Constant.GoodsConstant.RECYCLE_GOODS);
        return new ResultData(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 恢复回收站商品
     *
     * @param id
     */
    @Override
    public void recoverRecycleGoods(String id) {
        goodsMapper.recoverRecycleGoods(id);
    }

    /**
     * 删除回收商品
     *
     * @param id
     */
    @Override
    public void deleteRecycleGoods(String id) {
        goodsMapper.deleteRecycleGoods(id);
    }

    /**
     * 库存中商品
     *
     * @param goodsSearchVo
     * @return
     */
    @Override
    public ResultData warehouseList(GoodsSearchVo goodsSearchVo) {
        PageHelper.startPage(goodsSearchVo.getPage(), goodsSearchVo.getLimit());
        List<TbGoods> tbGoods = goodsMapper.warehouseList(goodsSearchVo);
        PageInfo<TbGoods> pageInfo = new PageInfo<>(tbGoods);
        return new ResultData(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 添加商品信息
     *
     * @param goodsVo
     */
    @Override
    public void addGoods(GoodsVo goodsVo) {
        //获取spu信息
        TbGoods goods = goodsVo.getGoods();
        //获取spu描述
        TbGoodsDesc goodsDesc = goodsVo.getGoodsDesc();
        //生成spu主键
        long l = idWorker.nextId();
        //初始化spu信息
        goods.setId(l + "");
        goods.setPublishStatus(Constant.GoodsConstant.UN_AWAY);
        goods.setIsRecycle(Constant.GoodsConstant.UN_RECYCLE);
        goods.setCreateTime(new Date());
        goods.setUpdateTime(new Date());
        //添加sku信息
        addSku(goodsVo, goods);
        //初始化商品描述信息
        goodsDesc.setGoodsId(l);
        //判断有无轮播图'
        if (goodsDesc.getImgListVo() != null && goodsDesc.getImgListVo().size() > 0) {
            //json转换
            String s = JSON.toJSONString(goodsDesc.getImgListVo());
            goodsDesc.setImgList(s);
        }
        //添加商品描述信息
        goodsDescMapper.addGoodsDesc(goodsDesc);
        //添加商品信息
        goodsMapper.insert(goods);

    }

    /**
     * 判断单多规格 获得sku
     *
     * @param spuId
     * @param skuId
     * @return java.lang.Object
     * @author HanSama
     * @date 2021/7/22 21:17
     */
    @Override
    public Object findSkuBySpuIdAndSkuId(Long spuId, Long skuId) {

        TbGoods spu = goodsMapper.findById(spuId);

        if (Constant.GoodsConstant.SINGLE_SPECIFICATION == spu.getSpecStatus()) {
            return goodsSpecMapper.findOneById(skuId);
        } else {
            return specsMapper.findOneById(skuId);
        }

    }

    @Override
    public TbGoods findOneById(String id) {

        return goodsMapper.findOne(id);
    }


    /**
     * @param goodsSearchVo 模糊条件
     * @param name          方法名称
     * @return
     */
    public PageInfo<TbGoods> pageAndFuzzy(GoodsSearchVo goodsSearchVo, String name) {
        PageHelper.startPage(goodsSearchVo.getPage(), goodsSearchVo.getLimit());
        List<TbGoods> goods = null;
        //判断是查询售空列表还是回收站
        if (Constant.GoodsConstant.SELL_OUT.equals(name)) {
            //售空列表
            goods = goodsMapper.findSelloutGoods(goodsSearchVo);
        } else {
            //回收站
            goods = goodsMapper.findRecycleGoods(goodsSearchVo);
        }
        PageInfo<TbGoods> pageInfo = new PageInfo<>(goods);
        return pageInfo;
    }


    @Override
    public Boolean addRecycle(String id) {
        return goodsMapper.addRecycle(id);
    }
}
